//
//  AwardCardViewController.m
//  SelfDriving
//
//  Created by apple on 16/2/3.
//  Copyright © 2016年 apple. All rights reserved.
//

#import "AwardCardViewController.h"
#import "BusinessService+WD.h"
#import "XhwPlayerVC.h"
@interface AwardCardViewController ()<UITableViewDataSource,UITableViewDelegate,BaseTableDetelage,UIActionSheetDelegate>
@property (weak, nonatomic) IBOutlet BaseTable *table;

@property (nonatomic, strong) AVAudioPlayer *aduioPlayer;

@property (nonatomic, strong) AVPlayer *player;

@property (nonatomic, strong) NSString *xhwCurrentMusicUrl;


@end

@implementation AwardCardViewController{
    UILabel *notlabel;
    NSMutableArray *data;
}
-(void)viewWillAppear:(BOOL)animated{
    [[NSNotificationCenter defaultCenter]
     addObserver:self
     selector:@selector(scollTop:)
     name:@"scollTop"
     object:nil];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationController.navigationBarHidden = NO;
    data = [[NSMutableArray alloc]init];
    _table.bdelegate = self;
    
    [self initData:0];
}
-(void)scollTop:(NSNotification *)not{
    if (data.count!=0) {
        [_table scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0] atScrollPosition:UITableViewScrollPositionTop animated:YES];
    }
}

-(void)initData:(int)index{
    NSMutableDictionary *dic = [[NSMutableDictionary alloc]init];
    [dic setObject:[NSNumber numberWithInt:index] forKey:@"page"];
    [[BusinessService shareInstance]dakalists:dic success:^(id result) {
        data = [_table result:result olddata:data index:index];
        if (notlabel) {
            [notlabel removeFromSuperview];
        }
        notlabel = (UILabel *)[_table notData];
        if (data.count == 0) {
            [self.view addSubview:notlabel];
        }
        [_table reloadData];
        
    } failure:^(id result) {
        [SVProgressHUD showErrorWithStatus:result];
    }];
    
    
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return data.count;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return 1;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    UITableViewCell *cell = [self tableView:tableView cellForRowAtIndexPath:indexPath];
    return cell.frame.size.height;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    UITableViewCell *cell =[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:@"cell"];
    cell.backgroundColor = colorBG;
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    LoginResponseModel *model = [data objectAtIndex:indexPath.section];
    UIView *bgview= [[UIView alloc]initWithFrame:CGRectMake(10, 10, SCRE_WIDTH-20, 300)];
    //基础UI
    
    bgview.backgroundColor = [UIColor whiteColor];
    bgview.layer.cornerRadius = 4;
    
    
    
    UILabel *name = [[UILabel alloc]initWithFrame:CGRectMake(65, 0, 180, 30)];
    name.text = model.nickname;
    name.font = [UIFont systemFontOfSize:15];
    [bgview addSubview:name];
    
    UIButton *isdaka = [[UIButton alloc]initWithFrame:CGRectMake(SCRE_WIDTH- 65, 5, 40, 25)];
    [isdaka setTitle:[model.isdaka isEqualToString:@"0"]?@"未打卡":@"已打卡" forState:UIControlStateNormal];
    isdaka.titleLabel.font = [UIFont systemFontOfSize:12];
    isdaka.backgroundColor = UIColorFromRGB(0x58B84A);
    [isdaka setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    isdaka.layer.cornerRadius = 5;
    isdaka.clipsToBounds = YES;
    isdaka.tag = indexPath.section;
    [isdaka addTarget:self action:@selector(adddaka:) forControlEvents:UIControlEventTouchUpInside];
    [bgview addSubview:isdaka];
    
    UILabel *logintime = [[UILabel alloc]initWithFrame:CGRectMake(65, 0, 120, 30)];
    //    logintime.text =[ValidateHelper dateFromDouble:[model.createtime doubleValue]];
    
    //2017-8-22修改 直接赋值model.createtime给logintime即可
    logintime.text = model.createtime;
    
    logintime.font = [UIFont systemFontOfSize:12];
    logintime.textColor = [UIColor grayColor];
    [bgview addSubview:logintime];
    
    UIImageView *headimg = [[UIImageView alloc]initWithFrame:CGRectMake(10, 10, 45, 45)];
    [headimg sd_setImageWithURL:[NSURL URLWithString:model.headsmall]
               placeholderImage:[UIImage imageNamed:@"notimgs"]];
    headimg.layer.cornerRadius = headimg.frame.size.width/2;
    headimg.clipsToBounds = YES;
    [bgview addSubview:headimg];
    [cell.contentView addSubview:bgview];
    
    int c = 0;
    if ([model.type intValue] == 0) {//文字
        //内容
        c = 70;
        MLEmojiLabel *elable = [[MLEmojiLabel alloc]initWithFrame:CGRectMake(10, 55, SCRE_WIDTH-20, c)];
        [ValidateHelper ReplaceMLEmojiLabel:model.content emojilable:elable];
        [bgview addSubview:elable];
        
    }else if ([model.type intValue] == 1){//图片
        c = 180;
//        UIImageView *img = [[UIImageView alloc]initWithFrame:CGRectMake(0, 55, SCRE_WIDTH-20, c)];
        UIImageView *img = [[UIImageView alloc]initWithFrame:CGRectMake(0, 60, SCRE_WIDTH-20, c)];
        [img sd_setImageWithURL:[NSURL URLWithString:model.content]
               placeholderImage:[UIImage imageNamed:@"notimgs"]];
        [bgview addSubview:img];
    }else if ([model.type intValue] == 2){//语音
        c = 180;
        UIImageView *img = [[UIImageView alloc]initWithFrame:CGRectMake(0, 60, SCRE_WIDTH-20, c)];
        [img sd_setImageWithURL:[NSURL URLWithString:model.content]
               placeholderImage:[UIImage imageNamed:@"notimgs"]];
        [bgview addSubview:img];
        UIImageView *playImg = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"音频"]];
        playImg.center = img.center;
        [bgview addSubview:playImg];
        
        
    }else if ([model.type intValue] == 3){//视频
        c = 180;
        UIImageView *img = [[UIImageView alloc]initWithFrame:CGRectMake(0, 60, SCRE_WIDTH-20, c)];
        [img sd_setImageWithURL:[NSURL URLWithString:model.content]
               placeholderImage:[UIImage imageNamed:@"notimgs"]];
        [bgview addSubview:img];
        
        UIImageView *playImg = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"图标---视频播放"]];
        playImg.center = img.center;
        [bgview addSubview:playImg];
    }
    
    
    BaseButton *btn = [[BaseButton alloc]initWithFrame:CGRectMake(0, c + 25, 40, 25)];
    [btn setImage:[UIImage imageNamed:@"图标---转发"] forState:UIControlStateNormal];
    btn.tag = indexPath.section;
    [btn addTarget:self action:@selector(fenxiang:) forControlEvents:UIControlEventTouchUpInside];
    [bgview addSubview:btn];
    
    
    
    CGRect bg = bgview.frame;
    bg.size.height = c + 55;
    bgview.frame = bg;
    
    CGRect cl =  cell.frame;
    cl.size.height = c + 60;
    cell.frame = cl;
    
    return cell;
}
//xhw2018-1-25加
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    LoginResponseModel *model = [data objectAtIndex:indexPath.section];
    
    if ([model.type intValue] == 3) {  //视频
        XhwPlayerVC *playerVC = [[XhwPlayerVC alloc] init];
        AVPlayer * player = [[AVPlayer alloc] initWithURL:[NSURL URLWithString:model.video]];
        playerVC.player = player;
        [self presentViewController:playerVC animated:YES completion:nil];
        
    }else if ([model.type intValue] == 2) { //音乐
        if (_player) {

            if ([_xhwCurrentMusicUrl isEqualToString:model.content]) {
                if (_player.rate == 1.0) {
                    [_player pause];
                }
                else {
                    [_player play];
                }
            }
            else {
                [_player pause];
                _player = nil;
                
                NSURL * audioUrl = [NSURL URLWithString:model.content];
                _xhwCurrentMusicUrl = model.content;
                AVPlayerItem *songItem = [[AVPlayerItem alloc] initWithURL:audioUrl];
                [songItem addObserver:self forKeyPath:@"status" options:NSKeyValueObservingOptionNew context:nil];
                _player = [[AVPlayer alloc] initWithPlayerItem:songItem];
            }
  
        }
        else {
            
            NSURL * audioUrl = [NSURL URLWithString:model.content];
            _xhwCurrentMusicUrl = model.content;
            AVPlayerItem *songItem = [[AVPlayerItem alloc] initWithURL:audioUrl];
            [songItem addObserver:self forKeyPath:@"status" options:NSKeyValueObservingOptionNew context:nil];
            _player = [[AVPlayer alloc] initWithPlayerItem:songItem];
        }

    }
}
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context {
    if ([keyPath isEqualToString:@"status"]) {
        switch (self.player.status) {
            case AVPlayerStatusUnknown:
                NSLog(@"未知状态，此时不能播放");
                break;
            case AVPlayerStatusReadyToPlay:
                NSLog(@"准备完毕，可以播放");
                [self.player play];
                break;
            case AVPlayerStatusFailed:
                NSLog(@"加载失败");
                break;
            default:
                break;
        }
    }
}

#pragma  mark 分享
-(void)fenxiang:(BaseButton *)btn{
    UIActionSheet * editActionSheet = [[UIActionSheet alloc] initWithTitle:nil delegate:self cancelButtonTitle:nil destructiveButtonTitle:nil otherButtonTitles:nil];
    editActionSheet.tag = btn.tag;
    [editActionSheet addButtonWithTitle:@"微博"];
    [editActionSheet addButtonWithTitle:@"微信好友"];
    [editActionSheet addButtonWithTitle:@"朋友圈"];
    [editActionSheet addButtonWithTitle:@"QQ空间"];
    [editActionSheet addButtonWithTitle:@"QQ"];
    [editActionSheet addButtonWithTitle:@"取消"];
    editActionSheet.cancelButtonIndex = editActionSheet.numberOfButtons - 1;
    [editActionSheet showFromTabBar:self.tabBarController.tabBar];
    editActionSheet.delegate = self;
}
-(void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex{
    
    if (buttonIndex + 1 >= actionSheet.numberOfButtons ) {
        return;
    }
    DTModel *model = [data objectAtIndex:actionSheet.tag];
    
    
    NSInteger snsName = UMSocialPlatformType_QQ;
    if (buttonIndex == 0) {
        snsName = UMSocialPlatformType_Sina;
    }else if (buttonIndex == 1){
        snsName = UMSocialPlatformType_WechatSession;
    }else if (buttonIndex == 2){
        snsName = UMSocialPlatformType_WechatTimeLine;
    }else if (buttonIndex == 3){
        snsName = UMSocialPlatformType_Qzone;
    }else if (buttonIndex == 4){
        snsName = UMSocialPlatformType_QQ;
    }
    //xhw12月19号加:友盟分享ios端必须是https开头的图片和视频地址
    UMSocialMessageObject *messageObject = [UMSocialMessageObject messageObject];
    
    
    [[AppDelegate shareDelegate]refuser:model.uid success:^(id as) {
        
        NSString *url = [NSString stringWithFormat:@"%@?type=3&id=%@",sharepageurl,model.id];
        LoginResponseModel *loginRes = (LoginResponseModel *)as;
        
        
        UMShareWebpageObject *shareObject = [UMShareWebpageObject shareObjectWithTitle:@"一米社交" descr:[NSString stringWithFormat:@"一米社交的[%@]打卡分享",loginRes.nickname] thumImage:[UIImage imageNamed:@"icon"]];
        //设置网页地址
        shareObject.webpageUrl = url;
        
        //分享消息对象设置分享内容对象
        messageObject.shareObject = shareObject;
        
        
        [[UMSocialManager defaultManager] shareToPlatform:snsName messageObject:messageObject currentViewController:self completion:^(id result, NSError *error) {
            if (error) {
                UMSocialLogInfo(@"************Share fail with error %@*********",error);
            }
            else {
                if ([result isKindOfClass:[UMSocialShareResponse class]]) {
                    UIAlertView * alertView = [[UIAlertView alloc] initWithTitle:@"成功" message:@"分享成功" delegate:nil cancelButtonTitle:@"好" otherButtonTitles:nil];
                    [alertView show];
                    NSMutableDictionary *dic= [[NSMutableDictionary alloc]init];
                    [dic setObject:@"1" forKey:@"type"];
                    [dic setObject:model.id forKey:@"content"];
                    [dic setObject:@"1" forKey:@"isopen"];
                    
                    [dic setObject:@"0" forKey:@"isweibo"];
                    [dic setObject:@"0" forKey:@"isweixin"];
                    [dic setObject:@"0" forKey:@"isweixinquan"];
                    [dic setObject:@"0" forKey:@"isqqzone"];
                    [dic setObject:@"0" forKey:@"isqq"];
                    
                    if (buttonIndex == 0) {
                        [dic setObject:@"1" forKey:@"isweibo"];
                    }else if (buttonIndex == 1){
                        [dic setObject:@"1" forKey:@"isweixin"];
                    }else if (buttonIndex == 2){
                        [dic setObject:@"1" forKey:@"isweixinquan"];
                    }else if (buttonIndex == 3){
                        [dic setObject:@"1" forKey:@"isqqzone"];
                    }else if (buttonIndex == 4){
                        [dic setObject:@"1" forKey:@"isqq"];
                    }
                    [dic setObject:@"1" forKey:@"isopen"];
                    [[BusinessService shareInstance]sharerecord:dic success:^(id result) {
                        
                    } failure:^(id result) {
                        
                    }];
                }
                else {
                    UMSocialLogInfo(@"response data is %@",data);
                }
            }
        }];
    }];
}

-(void)adddaka:(UIButton *)btn{
    LoginResponseModel *model = [data objectAtIndex:btn.tag];
    NSMutableDictionary *dic = [[NSMutableDictionary alloc] init];
    [dic setObject:model.id forKey:@"id"];
    [[BusinessService shareInstance]addDaka:dic success:^(id result) {
        [SVProgressHUD showSuccessWithStatus:@"打卡成功"];
        [_table Refresh];
    } failure:^(id result) {
        [SVProgressHUD showErrorWithStatus:result];
    }];
}

- (IBAction)backAction:(id)sender {
    [self.navigationController popViewControllerAnimated:YES];
    
}

@end
